<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/7
 * Time: 18:13
 */

namespace App\Process;


use App\Enums\UrlEnums;
use App\Library\Auth;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\Timer;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class Statistics extends AbstractProcess
{
    public function run($arg)
    {
        go(function ()use($arg){
            Timer::getInstance()->loop(1000*60*60*12,function (){
                $db = Mysql::defer('mysql');
                $leagues = $db->where('game','lol')->get('siam_league',null,'league_id,team_ids');
                //$team_ids = $db->where('game','lol')->getColumn('siam_team','team_id');
                $statisticUrl = UrlEnums::FJURL.UrlEnums::LOL_TEAM_LEAGUE_STAS."?league_id=%d&team_id=%d&version=2";
                foreach ($leagues as $league){
                    $team_ids = json_decode($league['team_ids']);
                    foreach ($team_ids as $team_id){
                        $teamStats = new HttpClient(sprintf($statisticUrl,$league['league_id'],$team_id));
                        list($s1, $s2) = explode(' ', microtime());
                        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                        $option = [
                            'path'      => UrlEnums::LOL_TEAM_LEAGUE_STAS,
                            'api_time'  => $microtime
                        ];
                        $header = Auth::getInstance($option)->header();
                        $resopnse = $teamStats->setHeaders($header,true,false)->get();
                        $data = $resopnse->getBody();
                        $data = json_decode($data,true);
                        if( $data['code'] != 200 || empty($data['game']) ) {
                            continue;
                        }
                        $data['data']['game'] = 'lol';

                        $value = $db->where('game','lol')->where('league_id',$data['data']['league_id'])
                            ->where('team_id',$team_id)->getValue('siam_teamleague_stats','id');
                        if( empty($stats) ){
                            $db->where('id',$value)->update('siam_teamleague_stats',$data['data']);
                        }else{
                            $db->insert('siam_teamleague_stats',$data['data']);
                        }
                    }
                }
            });
        });
    }
}